<template>
  <div class="grade-setting-wrapper">
    <el-tag
      type="danger"
      v-if="gradeData&&gradeData.length===0"
    >暂无任何定级</el-tag>
    <div class="grade-setting-content">
      <el-tag
        v-for="grade in dynamicTags"
        :key="grade"
        closable
        :disable-transitions="false"
        @close="handleClose(grade)"
      >{{grade}}</el-tag>
      <el-input
        class="input-new-tag"
        v-if="gradeInputVisible"
        v-model="gradeInputValue"
        ref="refgrade"
        size="small"
        @keyup.enter.native="handleInputConfirm"
        @blur="handleInputConfirm"
      >
      </el-input>
      <el-button
        v-else
        class="button-new-tag"
        size="small"
        @click="showInput"
      >+ 新增定级</el-button>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      gradeData: [],
      dynamicTags: [],
      gradeInputVisible: false,
      gradeInputValue: ''
    }
  },
  created () {
    this.getgradeData()
  },
  methods: {
    async handleInputConfirm () {
      const gradeInputValue = this.gradeInputValue
      if (gradeInputValue) {
        const { data } = await this.$http.post('/grade/add', { name: gradeInputValue })
        console.log(data)
        if (data.error_code === 0) {
          this.$message.success('定级添加成功')
          this.dynamicTags.push(gradeInputValue)
        } else {
          this.$message.error('该定级已存在，添加失败！')
        }
      }
      this.gradeInputValue = ''
      this.gradeInputVisible = false
    },
    async handleClose (tag) {
      const { data } = await this.$http.post('/grade/del', { name: tag })
      console.log(data)
      if (data.error_code === 1) {
        this.$message.error(data.msg)
      } else {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      }
    },
    showInput () {
      this.gradeInputVisible = true
      this.$nextTick(_ => {
        this.$refs.refgrade.$refs.input.focus()
      })
    },
    // 获取分类数据
    async getgradeData () {
      const { data } = await this.$http.get('/grade/getlist')
      this.gradeData = data.data
      this.gradeData.map(item => {
        this.dynamicTags.push(item.name)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/mixin";
.grade-setting-wrapper {
  display: flex;
  .grade-setting-content {
    display: flex;
    flex-flow: row wrap;
    @include tag(20px);
  }
}
</style>
